<?php

class BookController extends Controller{

    public function actionIncreDownloadTimes(){
        $bookId = Param::getInt('id');
        BookAR::increDownloadTimes($bookId);
        UserService::dumpBook($bookId);
    }
	
	public function actionObtainBook(){
		$bookId = Param::getInt('id');
		$book = BookService::obtainBook($bookId);
		//echo json_encode($book);
		$this->renderJson($book);
	}
	public function actionView($id = 0){
		FileUtil::appendClickedBookId($id);
		
		$smarty = Yii :: app()->smarty;
		if(!$smarty->is_cached('book/view.tpl','book_'.$id)){
			$book = BookAR::detail($id);
			 if(!$book){
	            throw new CHttpException(404,'您查看的图书不存在');
	        }
	        $data['book'] = $book;
	        $data['comments'] = CommentAR::commentsOfBook($id);
        	$data['author_otherbooks'] = BookAR::authorOtherBooks($id,$book['author']);
        	$smarty->cache_lifetime=Yii::app()->params['bookDetailCacheTime'];
	        $smarty->assign($data);
		}
		
		$this->renderCacheWithId('book/view.tpl',array(),'book_'.$id); 
	}

    public function actionIndex(){
        //We don't want execute this action. If the url is wrong,go site home
        $this->redirect(Yii::app()->params['siteHome']);
    }
	
	public function actionCategory($id_page = ''){
		$cidAndPageno = MyUtil::getCategoryIdAndPageNo($id_page);
		$smarty = Yii :: app()->smarty;
		if(!$smarty->is_cached('book/clist.tpl','bookclass_'.$id_page)){
			$topDownloads = BookService::topDownload(10,array('fk_category='.$cidAndPageno['cid']));
			$topClicked = BookService::topClicked(10,array('fk_category='.$cidAndPageno['cid']));
			$topComment = BookService::topComment(10,array('fk_category='.$cidAndPageno['cid']));
			$topNewUploadPage = BookService::topNewUploadPage($cidAndPageno);
			$cname = Yii::app()->params['categoryIdAndName'][$cidAndPageno['cid']];
	
	        $data = array(
	        	'cid'=>$cidAndPageno['cid'],
	        	'cname'=> $cname,
	            'top_downloads'=>$topDownloads,
	            'top_clicked'=>$topClicked,
	            'top_comment'=>$topComment,
	            'top_uploads'=>$topNewUploadPage,
	            );
	        $smarty->cache_lifetime=Yii::app()->params['clistCacheTime'];
	        $smarty->assign($data);
		}
		$this->renderCacheWithId('book/clist.tpl',array(),'bookclass_'.$id_page);
	}
	
	public function actionDownload($id = 0){
		UserService::dumpBook($id);
		$downloadInfo = BookService::download($id);
		
		$filePath = $downloadInfo['book_path'];
		$bookName = $downloadInfo['book_name'];
		$fileSize = $downloadInfo['book_size'];
		$ext = FileUtil::getExt($filePath); 
		
		header('Content-Disposition: attachment; filename='.$bookName.'.'.$ext);
		header('Content-Length:'.$fileSize);
		
		readfile(ltrim($filePath,'/'));
	}
	
	public function actionUpload(){
		//check necessary field
		$bookName = Param::getStr('book_name');
		$author = Param::getStr('author');
		$bookDesn = Param::getStr('book_desn');
		$categoryId = Param::getInt('selected_category_id',3);
		$ret = BookService::upload($bookName,$categoryId,$author, $bookDesn);
        if($ret['success']){
        	$smarty = Yii :: app()->smarty;
        	$smarty->clear_cache('index.tpl');
            $this->render('book/upload_ok.tpl',$ret);
        }else{
            $data = CategoryService::getAllCategorys();
            $this->render('book/upload.tpl',array('message'=>$ret['message'],'data'=>$data));
        }
	}
	
	public function actionUploadUI(){
    	if(User::id()==0){
    		Yii::app()->user->returnUrl='/book/uploadUI';
    		$this->redirect('/site/login');
    		exit;
    	}		
        $data = CategoryService::getAllCategorys();
		$this->render('book/upload.tpl',array('data'=>$data));
	}

    public function actionEditui($id = 0){
    	if(User::id()==0){
    		$this->redirect('/site/login');
    		exit;
    	}
        $book = BookService::findById($id);
        $this->render('book/edit.tpl',array('book'=>$book));
    }
    
    public function actionEdit(){
    	$bookId = Param::getInt('book_id');
    	$author = Param::getStr('author');
    	$bookDesn = Param::getStr('book_desn');
    	$ok = BookService::update($bookId,$author,$bookDesn);
    	$book = BookService::findById($bookId);
    	if($ok){
    		$this->redirect(array('view','id'=>$bookId));
    	}else{
    		$this->render('book/edit.tpl',array('book'=>$book,'message'=>'更新失败'));
    	}
    }
	
    //@fix param keyword has no value
	public function actionSearch($keyword = ''){
        $keyword_pageno = urldecode(basename($_SERVER['REQUEST_URI']));
        $keyword_pageno = urldecode($keyword_pageno);
        $arr = explode('_',$keyword_pageno);
        $keyword = $arr[0];
        $pageno = intval($arr[1]);
        if($pageno<=0){
            $pageno = 1;
        }
		FileUtil::appendKeyword($keyword);
        $page = BookService::searchBookAndAuthor($keyword,new Page($pageno,Yii::app()->params['searchBookPageSize']));
        $this->render('book/search.tpl',array('data'=>$page,'keyword'=>$keyword));
	}

    public function actionAddPanBook(){
        if(!isset($_REQUEST['content'])){
            $this->render('book/pan_book.tpl');
            return;
        }
        $content = $_POST['content'];
        $author = isset($_REQUEST['author']) ? $_REQUEST['author'] : '';
        $arr = explode("\n",$content);
        $len = count($arr);
        for($i=0;$i<$len;$i=$i+2){
            if(trim($arr[$i])==''){
                continue;
            }
            PanBookService::save115Book($arr[$i],$arr[$i+1],$author);
        }
        echo 'ok';
    }

    public function actionBatchUploadUI(){
        $this->render('book/batch_upload.tpl',array('user_id'=>User::id(),'user_name'=>User::name()));
    }

    public function actionBatchUpload(){
        // Work-around for setting up a session because Flash Player doesn't send the cookies
        if(!isset($_FILES['Filedata'])){
        		header("HTTP/1.1 500 Internal Server Error");
        		echo '请选择文件';
        	}
    	$user_id = Param::getInt('user_id');
    	$user_name = Param::getStr('user_name');
		$ret = BookService::batchUpload($user_id,$user_name,'Filedata');
		if(!$ret['success']){
        	header("HTTP/1.1 500 Internal Server Error");
        	echo $ret['message'];
        }
    }
}
